<?php

namespace App\Http\Controllers\Api;

use App\Apply;
use App\Craftsman;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class UserController extends Controller
{
    public function login(Request $request)
    {
        $user = User::where('username', $request->username)->first();
        if ($user && Hash::check($request->password, $user->password)) {
            return $user;
        } elseif (!$user) {
            return '用户名错误或不存在';
        } else {
            return '密码错误';
        }
    }

    public function registe(Request $data)
    {
        if (User::where('username', $data->username)->first()) {
            return '用户已存在';
        } else {
            return User::create([
                'username' => $data['username'],
                'password' => Hash::make($data['password']),
                'nickname' => $data['nickname'],
                'email' => $data['email'],
                'regis_time' => now(),
                'api_token' => Str::random(60),
            ]);
        }

    }

    public function reset(Request $request, User $user)
    {
        if (Hash::check($request->oldPwd, $user->password)) {
            $user->update([
                'password' => Hash::make($request->newPwd),
            ]);
            return response()->json([
                'status' => true,
                'msg' => '修改成功',
            ]);
        } else {
            return response()->json([
                'status' => false,
                'msg' => '原密码不正确',
            ]);
        }

    }

    public function show($user)
    {
        return User::withCount(['fan', 'follow', 'note', 'goods', 'blog', 'note_comment'])->find($user);
    }

    public function update(Request $request, User $user)
    {

        $user->update(
            [
                'nickname' => $request->name,
                'email' => $request->mail,
                'address' => $request->fullAddress,
                'bio' => $request->desc,
                'gender' => $request->gender,
                'phone' => $request->phone,
            ]
        );
        $user->save();

        return response()->json([
            'status' => 'success',
            'status_code' => 200,
            'data' => $user,
        ]);
    }

    public function apply(Request $request)
    {
        if ($request->type == 'check') {
            return Apply::where('user_id', $request->uid)->get();
        }
        $file = $request->file('image_src');
        $clientName = $_FILES['image_src']['name'];
        $extension = explode('.', $clientName);
        // 文件名加密
        $newName = md5(date('ymdhis') . $clientName) . "." . $extension[1];
        $file->move("storage/apply/{$request->uid}", $newName);

        return Apply::create([
            'user_id' => $request->uid,
            'zone_id' => $request->zid,
            'rank' => $request->rank,
            'certificate' => Str::start($newName, "http://craftsman.test/storage/apply/{$request->uid}/"),
            'apply_time' => now(),
        ]);
    }

    public function updateAvatar(Request $request, User $user)
    {
        $file = $request->file('file');
        $clientName = $_FILES['file']['name'];
        $extension = explode('.', $clientName);

        // 文件名加密
        $newName = md5(date('ymdhis') . $clientName) . "." . $extension[1];
        $file->move('storage/avatar', $newName);

        // 删除原文件
        if ($user->avatar !== '') {
            $oldFile = Str::after($user->avatar, 'http://craftsman.test/storage/avatar/');
            Storage::delete(Str::finish('public/avatar/', $oldFile));
        }

        // 存储文件绝对路径
        $user->avatar = Str::start($newName, 'http://craftsman.test/storage/avatar/');
        $user->save();

        return response()->json([
            'status' => 'success',
            'status_code' => 200,
            'data' => Str::start($newName, 'http://craftsman.test/storage/avatar/'),
            //返回加密的文件名称，用于前端显示
        ]);
    }

    public function updateCover(Request $request, User $user)
    {
        $file = $request->file('file');
        $clientName = $_FILES['file']['name'];
        $extension = explode('.', $clientName);

        // 文件名加密
        $newName = md5(date('ymdhis') . $clientName) . "." . $extension[1];
        $file->move('storage/cover', $newName);

        // 获取匠人实例，存储至匠人表
        $craftsman = Craftsman::find($user->craftsman_id);

        // 删除原文件
        if ($craftsman->image_src !== '') {
            $oldFile = Str::after($craftsman->image_src, 'http://craftsman.test/storage/cover/');
            Storage::delete(Str::finish('public/cover/', $oldFile));
        }

        // 存储文件绝对路径
        $craftsman->image_src = Str::start($newName, 'http://craftsman.test/storage/cover/');
        $craftsman->save();

        return response()->json([
            'status' => 'success',
            'status_code' => 200,
            'data' => Str::start($newName, 'http://craftsman.test/storage/cover/'),
            //返回加密的文件名称，用于前端显示
        ]);
    }

    public function getCraftsman(Craftsman $craftsman, $cid)
    {
        return $craftsman->with('zone')->where('id', $cid)->get()->pop();
    }

    public function updateShopName(Request $request, $cid)
    {
        Craftsman::find($cid)->update(['shop_name' => $request->shopName]);
    }
}
